#include "stdafx.h"
#include "Box2d.h"
#include "Point2d.h"
#include "Vector2d.h"
#include "GeomUtils.h"

using namespace stl;

CBox2D::CBox2D()
{
	x0 = y0 = x1 = y1 = 0.0;
}

CBox2D::CBox2D(double ix0, double iy0, double ix1, double iy1)
{
	x0 = ix0;
	y0 = iy0;
	x1 = ix1;
	y1 = iy1;
	normalize();
}

CBox2D::CBox2D(POINT2D leftBottomPt, POINT2D rightTopPt)
{
	x0 = leftBottomPt.x;
	y0 = leftBottomPt.y;
	x1 = rightTopPt.x;
	y1 = rightTopPt.y;
	normalize();
}

CBox2D::CBox2D(BOX2D b)
{
	x0 = b.x0;
	y0 = b.y0;
	x1 = b.x1;
	y1 = b.y1;
	normalize();
}

CBox2D::CBox2D(POINT2D leftBottomPt, VECTOR2D v)
{
	x0 = leftBottomPt.x;
	y0 = leftBottomPt.y;
	x1 = x0 + v.x;
	y1 = y0 + v.y;
	normalize();
}

CBox2D::~CBox2D()
{

}

CBox2D CBox2D::operator+(BOX2D b) const
{
	CBox2D box;
	box.x0 = (x0 < b.x0 ? x0 : b.x0);
	box.y0 = (y0 < b.y0 ? y0 : b.y0);
	box.x1 = (x1 > b.x1 ? x1 : b.x1);
	box.y1 = (y1 > b.y1 ? y1 : b.y1);
	return box;
}

void CBox2D::operator+=(BOX2D b)
{
	CBox2D box = (*this) + b;
	(*this) = box;
}

CBox2D CBox2D::operator&(BOX2D b) const
{
	double xx0 = (x0 > b.x0 ? x0 : b.x0);
	double yy0 = (y0 > b.y0 ? y0 : b.y0);
	double xx1 = (x1 < b.x1 ? x1 : b.x1);
	double yy1 = (y1 < b.y1 ? y1 : b.y1);

	if (xx1 > xx0 && yy1 > yy0)
	{
		return CBox2D(xx0, yy0, xx1, yy1);
	}
	return CBox2D();
}

void CBox2D::operator&=(BOX2D b)
{
	CBox2D box = (*this)&b;
	(*this) = box;
}

bool CBox2D::IsZero() const
{
	return GeIsZero(Width() * Height());
}

double CBox2D::Width() const
{
	return x1 - x0;
}

double CBox2D::Height() const
{
	return y1 - y0;
}

CBox2D::RelaShip CBox2D::GetRelationWith(BOX2D b) const
{
	CBox2D box = (*this)&b;
	if (box.IsZero())
	{
		return eSeparated;
	}
	return eIntersected;
}

void CBox2D::normalize()
{
	double xx0 = (x0 < x1 ? x0 : x1);
	double xx1 = (x0 > x1 ? x0 : x1);
	double yy0 = (y0 < y1 ? y0 : y1);
	double yy1 = (y0 > y1 ? y1 : y1);

	x0 = xx0;
	y0 = yy0;
	x1 = xx1;
	y1 = yy1;
}
